package com.fz.us.oa.web.controller.com;

import com.fz.us.admin.base.bean.BaseEnumManager;
import com.fz.us.admin.base.bean.jqgrid.JqGridFilter;
import com.fz.us.admin.base.bean.jqgrid.JqGridPager;
import com.fz.us.admin.base.bean.search.SearchEnum;
import com.fz.us.admin.base.bean.search.order.Order;
import com.fz.us.admin.base.bean.search.result.SearchResultPaging;
import com.fz.us.admin.base.utils.DataUtil;
import com.fz.us.admin.company.bean.FlowEnum;
import com.fz.us.admin.company.entity.Company;
import com.fz.us.admin.company.entity.TaskEntity;
import com.fz.us.admin.company.entity.User;
import com.fz.us.admin.company.service.DutyService;
import com.fz.us.admin.company.service.TaskEntityService;
import com.fz.us.oa.core.entity.com.OrderEntity;
import com.fz.us.oa.core.entity.common.FileManage;
import com.fz.us.oa.core.service.com.OrderEntityService;
import com.fz.us.oa.core.service.common.FileManagerService;
import com.fz.us.oa.web.controller.BaseController;
import com.fz.us.oa.web.shiro.bind.annotation.CurrentUser;
import com.fz.us.oa.web.spring.bind.annotation.RequestJsonParam;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ZhuChunXiao on 2017/7/19.
 */
@Controller
@RequestMapping(value = "/com/orderEntity")
public class OrderEntityController extends BaseController {
    private static final long serialVersionUID = -1403827277825151753L;

    @Autowired
    private OrderEntityService orderEntityService;
    @Autowired
    private DutyService dutyService;
    @Autowired
    private TaskEntityService taskEntityService;
    @Autowired
    private FileManagerService fileManagerService;

    /**
     * 新建，编辑页面
     */
    @RequestMapping(value = "input", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String input(@CurrentUser User user, Model model,String keyId,String draft,String index,String todo,String remind,String record) {
        if (StringUtils.isNotEmpty(keyId)){
            String fileId ="";
            OrderEntity order=orderEntityService.get(keyId);
            if(order.getFile() != null && order.getFile().size()>0){
                for(FileManage f:order.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            DecimalFormat sf = new DecimalFormat("0.00");
            model.addAttribute("money",sf.format(order.getMoney()));
            model.addAttribute("keyId", keyId);
            model.addAttribute("fileId", fileId);
            model.addAttribute("order", order);
        }
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        return "/com/orderEntity_input";
    }

    /**
     * 只读页面
     */
    @RequestMapping(value = "read", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String read(@CurrentUser User user, Model model,String keyId,String track,String draft,String index,String todo,String remind,String record) {
        if(StringUtils.isNotEmpty(keyId)) {
            String fileId ="";
            OrderEntity order=orderEntityService.get(keyId);
            if(order.getFile() != null && order.getFile().size()>0){
                for(FileManage f:order.getFile()){
                    fileId+=f.getId()+",";
                }
            }
            TaskEntity taskEntity = taskEntityService.getInfoByKeyId(keyId);
            int stepNo = taskEntity.getStepNo();
            String isEdit =  isEdit(keyId);
            DecimalFormat sf = new DecimalFormat("0.00");
            model.addAttribute("money",sf.format(order.getMoney()));
            model.addAttribute("isEdit", isEdit);
            model.addAttribute("fileId", fileId);
            model.addAttribute("order", order);
            model.addAttribute("stepNo", stepNo);
        }
        model.addAttribute("keyId", keyId);
        model.addAttribute("draft", draft);
        model.addAttribute("index", index);
        model.addAttribute("todo", todo);
        model.addAttribute("remind", remind);
        model.addAttribute("record", record);
        model.addAttribute("track", track);
        return "/com/orderEntity_read";
    }

    /**
     * 保存model操作
     */
    public OrderEntity saveModel(User user, String keyId, String contractId, String orderNo, Double money, String content,
                                 String issuedDate, String deliverDate, String remarks, String fileIds) throws ParseException {
        OrderEntity orderEntity =null;
        if(StringUtils.isBlank(keyId)){
            orderEntity =new OrderEntity();
            orderEntity.setCreater(user);
            orderEntity.setCompany(user.getCompany());
            orderEntity.setName("临时就叫这个名");
        }else{
            orderEntity =orderEntityService.get(keyId);
        }

        //TODO 合同信息表
        if(StringUtils.isNotEmpty(orderNo)){
            orderEntity.setOrderNo(orderNo);
        }
        if(money!=0){
            BigDecimal b = new BigDecimal(money);
            orderEntity.setMoney(b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue());
        }
        if(StringUtils.isNotEmpty(content)){
            orderEntity.setContent(content);
        }
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        if(StringUtils.isNotEmpty(issuedDate)){
            orderEntity.setIssuedDate(sdf.parse(issuedDate));
        }
        if(StringUtils.isNotEmpty(deliverDate)){
            orderEntity.setDeliverDate(sdf.parse(deliverDate));
        }
        if(StringUtils.isNotEmpty(remarks)){
            orderEntity.setRemarks(remarks);
        }
        List<FileManage> fileManageList = Lists.newArrayList();
        if(StringUtils.isNotEmpty(fileIds)){
            for(String f:fileIds.split(",")){
                fileManageList.add(fileManagerService.get(f.trim()));
            }
        }
        orderEntity.setFile(fileManageList);
        return orderEntity;
    }

    /**
     * 保存操作
     */
    @RequestMapping(value = "save", method = RequestMethod.POST)
    public Object save(@CurrentUser User user,
                       @RequestParam(required = false) String keyId,
                       String contractId,
                       String orderNo,
                       Double money,
                       String content,
                       String issuedDate,
                       String deliverDate,
                       String remarks,
                       String fileIds)throws ParseException {

        Map<String,Object> rMap=new HashMap<String,Object>();
        OrderEntity orderEntity =saveModel(user, keyId, contractId, orderNo, money, content, issuedDate, deliverDate, remarks, fileIds);

        if(StringUtils.isNotEmpty(keyId)){
            orderEntityService.update(orderEntity);
            rMap.put("message", "更新成功");
        } else {
            orderEntityService.save(orderEntity, "com.fz.us.oa.core.entity.com.OrderEntity");
            rMap.put("message", "保存成功");
        }
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 提交操作
     */
    @RequestMapping(value = "submit", method = RequestMethod.POST)
    public Object submit(@CurrentUser User user,
                         @RequestParam(required = false) String keyId,
                         String contractId,
                         String orderNo,
                         Double money,
                         String content,
                         String issuedDate,
                         String deliverDate,
                         String remarks,
                         String fileIds,
                         String curDutyId,
                         String comment) throws ParseException{

        if(!orderEntityService.checkOrderNo(orderNo,keyId)){
            return ajaxJson(resultService.fail("已经存在这个订单编号了！"));
        }

        Map<String,Object> rMap=new HashMap<String,Object>();
        OrderEntity orderEntity =saveModel(user,keyId,contractId,orderNo,money,content,issuedDate,deliverDate,remarks,fileIds);

        if (StringUtils.isNotEmpty(keyId)) {
            orderEntityService.approve(orderEntity, dutyService.get(curDutyId), comment);
        } else {
            orderEntityService.commit(orderEntity, "com.fz.us.oa.core.entity.com.OrderEntity", dutyService.get(curDutyId));
        }
        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    //审批
    @RequestMapping(value = "approve", method = RequestMethod.POST)
    public Object approve(@CurrentUser User user, String keyId,  String curDutyId, String comment){
        Map<String,Object> rMap=new HashMap<String,Object>();
        OrderEntity orderEntity = orderEntityService.get(keyId);
        orderEntityService.approve(orderEntity, dutyService.get(curDutyId), comment);

        rMap.put("message","提交成功");
        rMap.put("state","1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 退回
     * @return
     */
    @RequestMapping(value = "back", method = RequestMethod.POST)
    public Object back(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            OrderEntity orderEntity = orderEntityService.get(keyId);
            orderEntityService.back(orderEntity, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message", "退回成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }
    /**
     * 否决
     * @return
     */
    @RequestMapping(value = "deny", method = RequestMethod.POST)
    public Object deny(@CurrentUser User user, String keyId,String curDutyId, String comment) {
        if (StringUtils.isNotEmpty(keyId)) {
            OrderEntity orderEntity = orderEntityService.get(keyId);
            orderEntityService.deny(orderEntity, dutyService.get(curDutyId), comment);
        }
        Map<String,Object> rMap=new HashMap<String,Object>();
        rMap.put("message", "否决成功");
        rMap.put("state", "1");
        rMap.put("keyId", keyId);
        return ajaxJson(rMap);
    }

    /**
     * 列表
     */
    @RequestMapping(value = "list", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    @ResponseBody
    public Map<String, Object> list(@CurrentUser User user,Model model,
                                    String viewtype,
                                    JqGridPager pager,
                                    @RequestJsonParam(value = "filters", required = false) JqGridFilter filters) {
        Company company = user.getCompany();
        // 排序
        Order order = Order.order("orderNo", SearchEnum.OrderType.desc);

        SearchResultPaging searchResult = null;
        Map<String,Object> params = new HashMap<String,Object>();
        params.put("company", company);
        params.put("state", BaseEnumManager.StateEnum.Enable);
        if(StringUtils.isNotEmpty(viewtype)) {
            if (viewtype.equals("1")) {
                //订单下达
//                params.put("numStatus",0);
                params.put("cancel",false);
                searchResult = orderEntityService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.OrderEntity", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed},params);
            }else if(viewtype.equals("2")){
                //订单实施
//                params.put("numStatus",1);
                params.put("cancel",false);
                params.put("suspend",false);
                params.put("finish",false);
                searchResult = orderEntityService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.OrderEntity", new FlowEnum.ProcessState []{ FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("3")){
                //订单完成
//                params.put("numStatus",2);
                params.put("finish",true);
                params.put("cancel",false);
                params.put("suspend",false);
                searchResult = orderEntityService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.OrderEntity", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("4")){
                //订单暂停
                params.put("suspend",true);
                params.put("cancel",false);
                searchResult = orderEntityService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.OrderEntity", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }else if(viewtype.equals("5")){
                //订单取消
                params.put("cancel",true);
                searchResult = orderEntityService.paging(null,null,order,
                        "com.fz.us.oa.core.entity.com.OrderEntity", new FlowEnum.ProcessState []{FlowEnum.ProcessState.Finished},params);
            }
        }else{
            //所有单子
            searchResult = orderEntityService.paging(null,null,order,
                    "com.fz.us.oa.core.entity.com.OrderEntity",
                    new FlowEnum.ProcessState []{FlowEnum.ProcessState.Running, FlowEnum.ProcessState.Backed, FlowEnum.ProcessState.Finished, FlowEnum.ProcessState.Deny}, params);
        }

        List<OrderEntity> orderEntityList = searchResult.getList();
        ArrayList<Map<String, Object>> dataRows = new ArrayList<Map<String, Object>>();
        Map<String, Object> data = new HashMap<String, Object>();
        Map<String,Object> rMap;
        for(OrderEntity orderEntity: orderEntityList){
            rMap = new HashMap<String, Object>();
            rMap.put("id",orderEntity.getId());
            rMap.put("no",orderEntity.getOrderNo());
            rMap.put("issuedDate", DataUtil.DateToString(orderEntity.getIssuedDate()));
            rMap.put("deliverDate", DataUtil.DateToString(orderEntity.getDeliverDate()));
            rMap.put("state", orderEntity.getProcessState().value());
            rMap.put("rate", orderEntity.getRate()==null?"":orderEntity.getRate()+"%");
            rMap.put("trackDate",orderEntity.getTrackDate()==null?"":DataUtil.DateToString(orderEntity.getTrackDate()));
            rMap.put("suspendDate",orderEntity.getSuspendDate()==null?"":DataUtil.DateToString(orderEntity.getSuspendDate()));
            rMap.put("cancelDate",orderEntity.getCancelDate()==null?"":DataUtil.DateToString(orderEntity.getCancelDate()));
            rMap.put("finishDate",orderEntity.getFinishDate()==null?"":DataUtil.DateToString(orderEntity.getFinishDate()));
            rMap.put("red",orderEntity.isRed());
            dataRows.add(rMap);
        }
        data.put("dataRows", dataRows);
        data.put("page", searchResult.getPageNumber());
        data.put("rows", searchResult.getPageSize());
        data.put("records", searchResult.getTotalCount());
        data.put("total", searchResult.getPageCount());
        return data;
    }

    /**
     * 订单完成对话框
     */
    @RequestMapping(value = "finish/{keyId}",method = RequestMethod.GET)
    public String finish(@CurrentUser User user, Model model,
                         @PathVariable String keyId){
        model.addAttribute("keyId", keyId);

        return "/com/order_finish_dialog";
    }

    /**
     * 订单完成
     */
    @RequestMapping(value = "saveFinish/{keyId}",method = RequestMethod.POST)
    public Object saveFinish(@PathVariable String keyId, String finishDate, String finishText) throws ParseException{
        OrderEntity orderEntity=orderEntityService.get(keyId);
        orderEntity.setFinish(true);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
        orderEntity.setFinishDate(sdf.parse(finishDate));
        orderEntity.setFinishText(finishText);
        orderEntity.setNumStatus(2);

        return ajaxJson(orderEntityService.saveEntity(orderEntity));
    }

    /**
     * 订单完成只读页面
     */
    @RequestMapping(value = "finishRead/{keyId}", method = RequestMethod.GET, produces = MediaType.TEXT_HTML_VALUE)
    public String finishRead(@CurrentUser User user, Model model,
                             @PathVariable String keyId){
        OrderEntity orderEntity=orderEntityService.get(keyId);

        model.addAttribute("order", orderEntity);
        model.addAttribute("user", user);
        return "/com/orderFinish_read";
    }

    /**
     * 订单取消
     */
    @RequestMapping(value = "cancel", method = RequestMethod.POST)
    public Object cancel(@CurrentUser User user, String keyId){
        OrderEntity orderEntity=orderEntityService.get(keyId);
        if(!user.getId().equals(orderEntity.getCreater().getId())){
            return ajaxJson(resultService.fail("您不是该订单的提交人"));
        }
        orderEntity.setCancel(true);
        orderEntity.setCancelDate(new Date());
        orderEntityService.saveEntity(orderEntity);
        return ajaxJson(resultService.success("取消订单成功"));
    }

    /**
     * 订单暂停
     */
    @RequestMapping(value = "suspend", method = RequestMethod.POST)
    public Object suspend(@CurrentUser User user, String keyId){
        OrderEntity orderEntity=orderEntityService.get(keyId);
        if(!user.getId().equals(orderEntity.getCreater().getId())){
            return ajaxJson(resultService.fail("您不是该订单的提交人"));
        }
        orderEntity.setSuspend(true);
        orderEntity.setSuspendDate(new Date());
        orderEntityService.saveEntity(orderEntity);
        return ajaxJson(resultService.success("订单暂停成功"));
    }

    /**
     * 订单恢复
     */
    @RequestMapping(value = "recovery", method = RequestMethod.POST)
    public Object recovery(@CurrentUser User user, String keyId){
        OrderEntity orderEntity=orderEntityService.get(keyId);
        if(!user.getId().equals(orderEntity.getCreater().getId())){
            return ajaxJson(resultService.fail("您不是该订单提交人"));
        }
        orderEntity.setSuspend(false);
        orderEntity.setSuspendDate(null);
        orderEntityService.saveEntity(orderEntity);
        return ajaxJson(resultService.success("订单恢复成功"));
    }

}
